package com.lange.autocode.sysManager;

import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.core.utils.TreeUtils;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import cn.net.autocode.platform.busiModel.TreeBusiModel;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sysManager/sysDepart")
public class SysDepart {
    private final Dao dao;
    private final TreeBusiModel treeBusiModel;

    public SysDepart(Dao dao, TreeBusiModel treeBusiModel) {
        this.dao = dao;
        this.treeBusiModel = treeBusiModel;
    }

    @RequestMapping("queryTree")
    public ResultT queryTree(){
        String orgCode = UserThreadLocalUtils.getOrgCode();

        String sql = "select t.*,'dept' type from sys_departments t where org_code=? order by sort_no";
        JSONArray depts = dao.queryJSONArray(sql, orgCode);
        JSONArray deptTree = TreeUtils.commonTree(depts);

        JSONObject organ = new JSONObject();
        organ.put("type", "organ");
        organ.put("code", orgCode);
        organ.put("name", UserThreadLocalUtils.getOrgName());
        organ.put("id", orgCode);
        organ.put("children", deptTree);

        JSONArray rs = new JSONArray();
        rs.add(organ);

        return ResultT.success(rs);
    }

    @RequestMapping("saveDepartLeader")
    @Transactional
    public ResultT saveDepartLeader(@RequestBody JSONObject param){
        String deptId = param.getString("deptId");
        String leaderType = param.getString("leaderType");
        JSONArray users = param.getJSONArray("users");
        List<String> userNames = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < users.size(); i++) {
            JSONObject user = users.getJSONObject(i);
            String username = user.getString("username");
            String fullname = user.getString("fullname");
            if (i==0){
                stringBuilder.append(fullname);
            }else{
                stringBuilder.append(",").append(fullname);
            }
            userNames.add(username);
        }

        if (userNames.isEmpty()){
            dao.executeUpdate("delete from sys_department_leader where dept_id=? and leader_type=?",deptId,leaderType);
            switch (leaderType){
                case "fgld"://分管领导
                    dao.executeUpdate("update sys_departments set fgld=null where id=?",deptId);
                    break;
                case "xcdb":
                    dao.executeUpdate("update sys_departments set xcdb=null where id=?",deptId);
                    break;
                case "xcfg":
                    dao.executeUpdate("update sys_departments set xcfg=null where id=?",deptId);
                    break;
                default:
                    break;
            }
            JSONObject rs = new JSONObject();
            rs.put("leaderType", leaderType);
            rs.put("fullnames", "");
            return ResultT.success(rs);
        }else{
            dao.executeUpdate("delete from sys_department_leader where dept_id=? and leader_type=? and username not in (?)",deptId,leaderType,userNames);
            List<String> exists = dao.queryListValue("select username from sys_department_leader where dept_id=? and leader_type=?",String.class,deptId,leaderType);
            userNames.removeAll(exists);
            for(String username:userNames){
                dao.executeUpdate("insert into sys_department_leader(id,dept_id,username,leader_type) values(?,?,?,?)",IdWorker.ulid(),deptId,username,leaderType);
            }

            switch (leaderType){
                case "fgld"://分管领导
                    dao.executeUpdate("update sys_departments set fgld=? where id=?",stringBuilder.toString(),deptId);
                    break;
                case "xcdb":
                    dao.executeUpdate("update sys_departments set xcdb=? where id=?",stringBuilder.toString(),deptId);
                    break;
                case "xcfg":
                    dao.executeUpdate("update sys_departments set xcfg=? where id=?",stringBuilder.toString(),deptId);
                    break;
                default:
                    break;
            }

            JSONObject rs = new JSONObject();
            rs.put("leaderType", leaderType);
            rs.put("fullnames", stringBuilder.toString());
            return ResultT.success(rs);
        }

    }

    @RequestMapping("saveServgrpUser")
    public ResultT saveServgrpUser(@RequestBody JSONObject param){
        JSONArray userArray = param.getJSONArray("userList");
        List<String> userList = userArray.toList(String.class);
        String orgCode = param.getString("orgCode");
        String dept = param.getString("dept");
        String servgrp = param.getString("servgrp");
        //删除不存在的用户
        if(userList.isEmpty()){
            dao.executeUpdate("delete from sys_servgrp_user where org_code=? and dept=? and servgrp=?",orgCode,dept,servgrp);
            return ResultT.success();
        }else{
            dao.executeUpdate("delete from sys_servgrp_user where org_code=? and dept=? and servgrp=? and username not in (?)",orgCode,dept,servgrp,userList);
        }
        //添加表中不存在的用户
        List<String> existsUser = dao.queryListValue("select username from sys_servgrp_user where org_code=? and dept=? and servgrp=?",String.class,orgCode,dept,servgrp);
        userList.removeAll(existsUser);
        for(String username:userList){
            dao.executeUpdate("insert into sys_servgrp_user(id,username,org_code,dept,servgrp) values(?,?,?,?,?)", IdWorker.ulid(),username,orgCode,dept,servgrp);
        }
        return ResultT.success();
    }


    @RequestMapping("nodeDrop")
    @Transactional
    public ResultT nodeDrop(@RequestBody JSONObject param){
        JSONObject  draggingNode = param.getJSONObject("draggingNode");
        JSONObject  dropNode = param.getJSONObject("dropNode");
        String dropType = param.getString("dropType");
        if(dropNode.getString("type").equals("organ")){
            //拖拽到第一个节点
            String draggingNodeId = draggingNode.getString("id");
            dao.executeUpdate("update sys_departments set parent_id=?,sort_no=0 where id=?",null,draggingNodeId);
            String orgCode = dropNode.getString("code");
            List<String> ids = dao.queryListValue("select id from sys_departments where org_code=? and parent_id is null and id<>? order by sort_no",String.class,orgCode,draggingNodeId);
            for(int i=0;i<ids.size();i++){
                String id = ids.get(i);
                dao.executeUpdate("update sys_departments set sort_no=? where id=?",i+1,id);
            }
            return ResultT.success();
        }else{
            String rs = treeBusiModel.nodeDrop(draggingNode,dropNode,dropType,"sys_departments");
            if (rs.equals("success")){
                return ResultT.success();
            }else{
                return ResultT.fail(rs);
            }
        }
    }


}
